#include "definition.h"
#include "DocInfoSqlite.h"

#define LITERUN(cmd, e) m_rc = cmd; if( m_rc ) { e;};

static int callback(void *NotUsed, int argc, char **argv, char **azColName){
  int i;
  for(i=0; i<argc; i++){
    printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
  }
  printf("\n");
  return 0;
}

DocInfoSqlite::DocInfoSqlite(wxString dpath)
:   DocInfoDBBase(dpath), m_db(NULL), m_dbPath(dpath)
{

};

DocInfoSqlite::~DocInfoSqlite()
{
    ReleaseDB();
}

void DocInfoSqlite::CreateDB()
{
    const wchar_t create_table[] = L"create table document"
        L"( id int index, name string, path string, filename string"
        L"  size int, comment string );";

    exeSql(create_table);
}

void DocInfoSqlite::ReleaseDB()
{
    if(m_db)
        sqlite3_close(m_db);
    m_db = NULL;
}

void DocInfoSqlite::LoadDB()
{
    assert( !m_db );

    m_rc = sqlite3_open( m_dbPath.ToUTF8(), &m_db );
    if( m_rc )
    {
        sqlite3_close( m_db );
        m_db = NULL;
        throw std::logic_error( "Error while opening sqlite database" );
    }
}

void DocInfoSqlite::exeSql(STRING sqlcmd)
{
    assert( m_db );

    m_rc = sqlite3_exec(m_db, sqlcmd, callback, NULL, &m_errMsg);
    if( m_rc )
    {
        throw std::logic_error("Error while executing sql command");
    }
}

bool DocInfoSqlite::IsOK()
{
    return m_db != NULL;
}
